import time
import paho.mqtt.subscribe as subscribe

# MQTT配置（添加了用户名和密码）
MQTT_BROKER = "127.0.0.1"
MQTT_PORT = 1883
MQTT_TOPIC = "tcp/data/forward"
MQTT_USERNAME = "admin"  # EMQ X用户名
MQTT_PASSWORD = "chdcxy5308996"  # EMQ X密码

# 数据保存路径
FILE_PATH = "mqtt_data.txt"


def on_message(client, userdata, message):
    """MQTT消息回调函数"""
    payload = message.payload.decode("utf-8")#message.payload 是获取消息内容的唯一入口
    print(f"收到MQTT消息: {payload}，主题: {message.topic}")

    # 写入文本文件
    with open(FILE_PATH, "a", encoding="utf-8") as f:
        f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())} - 接收到数据: {payload}\n")


if __name__ == "__main__":
    try:
        # 订阅MQTT主题（添加认证信息）
        subscribe.callback(
            on_message,
            MQTT_TOPIC,
            hostname=MQTT_BROKER,
            port=MQTT_PORT,
            auth={'username': MQTT_USERNAME, 'password': MQTT_PASSWORD}
        )
    except KeyboardInterrupt:
        print("客户端停止订阅")
    except Exception as e:
        print(f"订阅错误: {e}")